<?php

namespace App\Http\Requests;

use App\Helpers\ResponseHelper;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\Request;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        $user = Request::user();
        return [
            'username' => 'required|string|max:255',
            'mobile' => ['required', 'regex:/^1[3-9]\d{9}$/', 'unique:users,mobile,' . $user->id],
            'avatar' => 'required|string',
        ];
    }

    public function messages(): array
    {
        return [
            'username.required' => '请填写昵称.',
            'avatar.required' => '请上传头像.',
            'mobile.required' => '请填写手机号.',
            'mobile.regex' => '手机号格式不正确.',
            'mobile.unique' => '手机号已存在.',
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        $errors = $validator->errors();
        // 返回自定义的 JSON 格式
        throw new HttpResponseException(ResponseHelper::error(message: $errors));
    }
}
